<template>
  <s-layout
      title="我的订单"
      navbar="custom"
      :showLeftButton="true"
      navbarMode="normal"
      :bgStyle="template.style?.background"
      :navbarStyle="template.style?.navbar"
      onShareAppMessage
      :showFloatButton="true"
  >
    <view>
      <view class="tick-tab-list">
        <view
            class="tick-tab-item"
            @click="getTab(index)"
            :class="{ 'tab-sel': index === tabIndex }"
            v-for="(value, index) in tabList"
            :key="index"
        >
          {{ value.text }}
          <view class="bottoms" v-if="index === tabIndex"></view>
        </view>
      </view>
      <scroll-view
          scroll-y="true"
          class="scroll-Y"
          @scrolltolower="handleScrollToLower"
          lower-threshold="100"
      >
        <view
            class="tick-lists"
            v-for="(value, index) in dataList"
            :key="index"
            @click="getDetails(value)"
        >
          <view class="tick-list-top">
            <view class="tock-shop-name">{{ value.backParams?.cinemaName }}</view>
            <view class="tock-list-status" v-if="value.status === '1'">待支付</view>
            <view class="tock-list-status" v-if="value.status === '2'">已出票</view>
            <view class="tock-list-status" v-if="value.status === '3'">出票失败</view>
            <view class="tock-list-status" v-if="value.status === '4'">待出票</view>
          </view>
          <view class="tick-list-info">
            <view class="film-cover">
              <image :src="value.backParams?.movieLogo || value.backParams?.filmPic"></image>
            </view>
            <view class="film-list-ret">
              <view class="film-name">{{ value.movieInfo?.name || value.backParams.filmName}}</view>
              <view class="film-time"
              >{{ value.movieSize || 0 }}张 I
                {{ value.createTime }}
              </view>
              <view class="film-time"> 订单编号：{{ value.orderNumber }}</view>
            </view>
          </view>
        </view>
        <s-empty
            v-if="dataList.length === 0"
            icon="https://picture-1326598115.cos.ap-nanjing.myqcloud.com/2025/09/2489e93becde3c4254a1d5cda65818f8fcorder-empty.png"
            text="暂无数据"
        ></s-empty>
      </scroll-view>
    </view>
  </s-layout>
</template>

<script setup>
import {computed, ref} from 'vue';
import {onLoad, onReachBottom} from '@dcloudio/uni-app';
import sheep from "@/sheep";

// 响应式数据声明
const tabList = ref([
  {text: "全部"},
  {text: "待付款"},
  {text: "已出票"},
  {text: "出票失败"},
  {text: "待出票"},
]);

const tabIndex = ref(0);
const page = ref(1);
const dataList = ref([]);
const isPage = ref(true);
const isLoading = ref(false); // 新增：加载状态标记

// 计算属性
const template = computed(() => {
  return sheep.$store("app").template.user;
});

// 生命周期钩子
onLoad((opt) => {
  // 初始化页面数据
  if (opt.status) {
    if (opt.status === "1") {
      tabIndex.value = 0;
      getData();
    } else {
      tabIndex.value = 2;
      getData(opt.status);
    }
  } else {
    getData();
  }
});

// 新增触底事件处理函数
const handleScrollToLower = () => {
  console.log('scroll-view触底事件触发');
  // 直接实现加载逻辑，不调用onReachBottom
  if (isPage.value && !isLoading.value) {
    page.value++;
    getData();
  } else {
    console.log('触底但不加载 - 是否有下一页:', isPage.value, '加载状态:', isLoading.value);
  }
};

// 删除onReachBottom生命周期注册
onReachBottom(() => {
  console.log('页面触底事件触发 - 当前页码:', page.value);
  if (isPage.value && !isLoading.value) {
    page.value++;
    getData();
  } else {
    console.log('触底但不加载 - 是否有下一页:', isPage.value, '加载状态:', isLoading.value);
  }
});

// 获取订单详情
const getDetails = (value) => {
  try {
    // 订单状态判断
    switch (String(value.status)) {
      case '4':
        uni.showToast({icon: 'none', title: '订单正在出票，请耐心等待'});
        return;
      case '3':
        uni.showToast({icon: 'none', title: '订单出票失败'});
        return;
      case '2':
        if (value.channel === '3') {
          sheep.$router.go('/pages/movie/order-detail',{orderNumber: value.orderNumber});
        } else if (value.channel === 'xk') {
          sheep.$router.go(`/pages/xk-movie/order-detail?orderId=${value.orderNumber}`);
        }
        break;
      case '1':
        if (value.channel === '3') {
          sheep.$router.go(`/pages/movie/pay?orderNumber=${value.orderNumber}`);
        } else if (value.channel === 'xk') {
          sheep.$router.go(`/pages/xk-movie/pay?orderId=${value.orderNumber}`);
        }
        break;
      default:
        console.log('未知订单状态:', value.status);
    }
  } catch (error) {
    console.error('订单详情查看失败:', error);
    uni.showToast({icon: 'error', title: '查看详情失败'});
  }
};

// 切换标签页
const getTab = (index) => {
  if (tabIndex.value !== index) {
    tabIndex.value = index;
    page.value = 1;
    isPage.value = true;
    dataList.value = [];

    // 使用对象映射替代多个 if-else 判断
    const statusMap = ['', '1', '2', '3', '4', '', '5'];
    const status = statusMap[index];

    if (status !== undefined) {
      getData(status || '');
    }
  }
};

// 获取订单数据
const getData = async (status = '') => {
  if (isLoading.value) return; // 防止重复请求
  isLoading.value = true;
  try {
    const params = {
      status: status,
      page: page.value,
      size: 10
    };
    const res = await sheep.$api.xkMovie.getXkMovieList(params);
    if (res.code === 200) {
      let currentData = res.data.content; // 修改为let变量
      currentData = currentData.map((item) => {
        if (typeof item.backParams === 'string') {
          item.backParams = JSON.parse(item.backParams);
        }
        if (typeof item.movieInfo === 'string') {
          item.movieInfo = JSON.parse(item.movieInfo);
        }
        return item;
      });
      if (page.value === 1) {
        dataList.value = currentData;
      } else {
        dataList.value = dataList.value.concat(currentData);
      }
      // 恢复下一页判断逻辑
      isPage.value = currentData.length === params.size;
      console.log('dataList.value:   ', dataList.value);
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    uni.showToast({icon: 'error', title: '网络请求失败'});
  } finally {
    isLoading.value = false; // 无论成功失败都关闭加载状态
  }
};
</script>

<style lang="scss" scoped>
page {
  background-color: #f4f5f7;
}

.scroll-Y {
  margin-top: 20rpx;
  /* 使用固定高度测试，排除变量计算问题 */
  height: calc(100vh - 200rpx);
  /* 确保滚动条可见 */
  overflow-y: auto;
  /* 添加背景色便于观察容器范围 */
  background-color: rgba(244, 245, 247, 0.5);
}

.tick-tab-list {
  display: flex;
  background-color: #ffffff;
  align-items: center;
  padding: 200rpx 0 30rpx;

  .tick-tab-item {
    width: 16.66%;
    text-align: center;
    color: #636775;
    font-size: 28rpx;
    position: relative;
  }

  .tab-sel {
    color: #2d3039 !important;
    font-size: 32rpx !important;
    font-weight: 550;
  }

  .bottoms {
    position: absolute;
    bottom: -30rpx;
    right: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 52rpx;
    height: 8rpx;
    background-color: #fe602b;
  }
}

.tick-lists {
  margin: 20rpx 32rpx 0 32rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx 32rpx;

  .tick-list-top {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .tock-shop-name {
      color: #636775;
      font-size: 28rpx;
      width: 80%;
    }

    .tock-list-status {
      color: #fe602b;
      font-size: 28rpx;
    }
  }

  .tick-list-info {
    margin-top: 28rpx;
    display: flex;

    .film-cover {
      width: 116rpx;
      height: 140rpx;

      image {
        width: 116rpx;
        height: 140rpx;
        border-radius: 10rpx;
      }
    }

    .film-list-ret {
      margin-left: 20rpx;

      .film-name {
        color: #2d3039;
        font-size: 32rpx;
        font-weight: 550;
        margin-top: 8rpx;
      }

      .film-time {
        color: #636775;
        font-size: 28rpx;
        margin-top: 16rpx;
      }
    }
  }
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
  color: #636775;
  font-size: 28rpx;
}

.loading-text {
  margin-left: 10rpx;
}
</style>
